﻿' Copyright (c) Microsoft Corporation.  All rights reserved.
' The following example shows a very quick way to get started with the ADO.NET Entity Framework.

Imports GettingStarted_VB.MyTravelModel

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' don't do anything during postback
        If IsPostBack Then
            Return
        End If

        Try

            ' the short lived MyTravelPostEntities creates/destroys the connection
            ' for the life of the using statement.
            Using entities As New MyTravelPostEntities
                Dim post = (From bp In entities.BlogPosts.Include("Comments.Person") _
                           Where bp.Comments.Count() > 0 _
                           Select bp).First()

                ' put the blog entry in the text.
                textBlogEntry.Text = post.BlogEntry

                ' update all these items first
                UpdateComments(post)

                ViewState("BlogPost") = post
            End Using
        Catch ex As Exception
            ' add your own exception handling here, for connection or some potential but.
            Throw ex
        End Try
    End Sub

    Private Sub ReloadPage()
        ' clear out and then go to the travelpage.
        Response.Redirect("Default.aspx")
    End Sub

    Private Sub UpdateComments(ByVal post As BlogPost)
        ' using annoymous types, I can get the comments and the person
        Dim comments = From c In post.Comments _
                           Select c.Person.Name, c.CommentText
        gridViewComment.DataSource = comments
        gridViewComment.DataBind()
    End Sub


    Protected Sub buttonUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonUpdate.Click
        Try
            ' just for fun loop through all the comments and add a *
            ' the short lived MyTravelPostEntities creates/destroys the connection
            ' for the life of the using statement.
            Using entities As New MyTravelPostEntities
                ' deserializing and then reattaching allows the statemanager
                ' to track this post and the changes. 
                Dim post = DirectCast(ViewState("BlogPost"), BlogPost)
                entities.Attach(post)

                ' if we are updating, we may already have the comments,
                ' no need to go get these again.
                If post.Comments.Count() = 0 Then
                    ' go get the comments with the person, then attach.
                    Dim comments = From c In entities.Comments.Include("Person") _
                                       Where c.BlogPost.BlogPostID = post.BlogPostID _
                                       Select c
                    post.Comments.Attach(comments)
                End If

                ' loop through and add the *
                For Each c In post.Comments
                    c.CommentText += "*"
                Next

                ' once you have the reference, the properties are changed
                ' tracked so modifications are update during SaveChanges
                Try
                    entities.SaveChanges()
                Catch ex As OptimisticConcurrencyException
                    ' catching this exception allows you to 
                    ' refresh entities with either store/client wins
                    ' project the entities into this failed entities.
                    Dim failedEntities = From e1 In ex.StateEntries _
                                         Select e1.Entity

                    ' Note: in future you should be able to just pass the opt.StateEntities in to refresh.
                    entities.Refresh(RefreshMode.ClientWins, failedEntities.ToList())
                    entities.SaveChanges()
                End Try

                UpdateComments(post)
                ViewState("BlogPost") = post
            End Using
        Catch ex As Exception
            ' add your own exception handling here.
            Throw ex
        End Try

        ' Reload page to fix any F5 issues that may come up.
        ReloadPage()

    End Sub

    Protected Sub buttonCreate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonCreate.Click
        Try
            ' the short lived MyTravelPostEntities creates/destroys the connection
            ' for the life of the using statement.
            Using entities As New MyTravelPostEntities()
                ' deserializing and then reattaching allows the statemanager
                ' to track this post and the changes.
                Dim post = DirectCast(ViewState("BlogPost"), BlogPost)
                entities.Attach(post)

                ' if we are updating, we may already have the comments,
                ' no need to go get these again.
                If post.Comments.Count() = 0 Then
                    ' go get the comments with the person, then attach.
                    Dim comments = From c In entities.Comments.Include("Person") _
                                       Where c.BlogPost.BlogPostID = post.BlogPostID _
                                       Select c
                    post.Comments.Attach(comments)
                End If

                ' creating a new comment and add the first person
                ' the person does a query to fetch the people
                ' but you could also add the people to view state and attach
                ' then when setting you would just create the relationship
                Dim newComment As New Comment With {.CommentText = textComment.Text, _
                                                    .Person = entities.People.First()}

                post.Comments.Add(newComment)

                Try
                    entities.SaveChanges()
                Catch ex As OptimisticConcurrencyException
                    ' catching this exception allows you to 
                    ' refresh entities with either store/client wins
                    ' project the entities into this failed entities.
                    Dim failedEntities = From e2 In ex.StateEntries _
                                         Select e2.Entity

                    ' Note: in future you should be able to just pass the opt.StateEntities in to refresh.
                    entities.Refresh(RefreshMode.ClientWins, failedEntities.ToList())
                    entities.SaveChanges()
                End Try

                textComment.Text = ""
                UpdateComments(post)
                ViewState("BlogPost") = post
            End Using
        Catch ex As Exception
            ' add your own exception handling here.
            Throw ex
        End Try
        ' Reload page to fix any F5 issues that may come up.
        ReloadPage()
    End Sub

    Protected Sub buttonDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonDelete.Click
        Try
            ' just for fun loop through all the comments and add a *
            ' the short lived MyTravelPostEntities creates/destroys the connection
            ' for the life of the using statement.
            Using entities As New MyTravelPostEntities

                ' deserializing and then reattaching allows the statemanager
                ' to track this post and the changes.
                Dim post = DirectCast(ViewState("BlogPost"), BlogPost)
                entities.Attach(post)

                ' first to get the comment and delete.
                Dim toDelete = post.Comments.First()
                entities.DeleteObject(toDelete)

                Try
                    ' once you have the reference, the properties are changed
                    ' tracked so modifications are update during SaveChanges
                    entities.SaveChanges()
                Catch ex As OptimisticConcurrencyException
                    ' catching this exception allows you to 
                    ' refresh entities with either store/client wins
                    ' project the entities into this failed entities.
                    Dim failedEntities = From e3 In ex.StateEntries _
                                         Select e3.Entity

                    ' Note: in future you should be able to just pass the opt.StateEntities in to refresh.
                    entities.Refresh(RefreshMode.ClientWins, failedEntities.ToList())
                    entities.SaveChanges()
                End Try

                UpdateComments(post)
                ViewState("BlogPost") = post
            End Using
        Catch ex As Exception
            ' add your own exception handling here, for connection or some potential but.
            Throw ex
        End Try
        ' Reload page to fix any F5 issues that may come up.
        ReloadPage()
    End Sub
End Class